#include <iostream>
#include <string>
#include <unistd.h>
#include <assert.h>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

int main()
{
    int pipefd[2] = {0};  // 0 就是读， 1 就是写
    int n = pipe(pipefd); // 1.打开管道文件，返回文件描述符存入pipefd
    assert(n != -1);
    (void)n;

    pid_t id = fork(); // 2. 创建子进程
    assert(id != -1);

    if (id == 0) // id == 0 子进程
    {
        // 子进程关闭写端文件描述符
        close(pipefd[1]);
        char ReadBuffer[1024 * 8] = {0};
        while (true)
        {
            // 根据文件描述符pipefd[0] 读取父进程写入的数据
            ssize_t s = read(pipefd[0], ReadBuffer, sizeof(ReadBuffer) - 1);
            if (s > 0)
            {
                cout << "child get a message [ " << getpid() << " ] " << ReadBuffer << endl;
            }
            else if (s == 0)
            {
                cout << "write is quit, me too!" << endl;
                break;
            }
        }
        close(pipefd[0]);
        exit(0);
    }
    // 父进程
    close(pipefd[0]); // 1.关闭读端的文件描述符
    int count = 0;
    string str = "我是父进程，我给你发消息了!\n";
    char SendBuffer[1024 * 8];
    while (true)
    {
        //sleep(1);
        // 构建一个变化的字符串
        snprintf(SendBuffer, sizeof(SendBuffer), "%s[%d]: %d", str.c_str(), getpid(), count++);
        // 写入数据
        write(pipefd[1], SendBuffer, strlen(SendBuffer));
        // if (count == 5)
        // {
        //     cout << "父进程退出 , 父进程pid: " << getpid() << endl;
        //     break;
        // }
    }
    close(pipefd[1]);
    pid_t ret = waitpid(id, nullptr, 0);
    cout << "id:" << id << "ret::" << ret << endl;
    (void)ret;
    return 0;
}